﻿using Microsoft.Win32;
using Pegasus.Diagnostics;
using System;
using System.Collections;
using System.IO;

namespace Pegasus.IO
{
	/// <summary>
	/// Static class that contains misc methods for accessing information about a file
	/// </summary>
	public class FileInfoHelper
	{
		/// <summary>
		/// Get the Title of the a document
		/// </summary>
		/// <param name="filename">Full path to the file</param>
		/// <returns>Title of the document</returns>
		public static string GetDocumentTitle( string filename )
		{
			// Check params
			ParamCode.AssertNotEmpty( filename, "filename" );

			// TODO Get title for office docs and NTFS aux streams
			return Path.GetFileNameWithoutExtension( filename );
		}

		/// <summary>
		/// 
		/// </summary>
		/// <param name="longFilename"></param>
		/// <returns></returns>
		public static string CreateEightDotThreeFilename( string longFilename )
		{
			return CreateEightDotThreeFilename( longFilename, string.Empty );
		}

		/// <summary>
		/// 
		/// </summary>
		/// <param name="longFilename"></param>
		/// <param name="usedFilenames"></param>
		/// <returns></returns>
		public static string CreateEightDotThreeFilename( string longFilename, ArrayList usedFilenames )
		{
			bool done = false;
			string uniqueAppend = string.Empty;
			string shortFilename = string.Empty;
			int count = 0;

			while( !done )
			{
				shortFilename = CreateEightDotThreeFilename( longFilename, uniqueAppend );
				if( usedFilenames.Contains( shortFilename ) )
				{
					count++;
					uniqueAppend = count.ToString();
				}
				else
				{
					usedFilenames.Add( shortFilename );
					done = true;
				}
			}

			return shortFilename;
		}

		/// <summary>
		/// 
		/// </summary>
		/// <param name="longFilename"></param>
		/// <param name="uniqueAppend"></param>
		/// <returns></returns>
		private static string CreateEightDotThreeFilename( string longFilename, string uniqueAppend )
		{
			string filename = Path.GetFileNameWithoutExtension( longFilename );
			string ext = Path.GetExtension( longFilename );
			
			int len = Math.Min( 8 - uniqueAppend.Length, filename.Length );
			len = Math.Max( 0, len );
			filename = filename.Substring( 0, len );

			len = Math.Min( 3, ext.Length - 1 );
			len = Math.Max( 0, len );
			ext = ext.Substring( 1, len );

			return string.Format( "{0}{1}.{2}", filename, uniqueAppend, ext );
		}
	}
}
